/*
* 苏州海管家物流科技有限公司（https://www.hgj.com/）.
* 苏公网安备32059002003385号 © 2015-2022 Hgj.com All Rights Reserved. | 苏ICP备15030950号.
* @Date: 2022.03.18.
* @Author
* @Description 企点 管理后台 - 舱位交易 - 经销商列表 模块.
**/
<template>
  <Layout>
    <section class="p-5 bg-white mb-5">
      <!-- form -->
      <el-form
        ref="queryForm"
        label-width="120px"
        class="flex"
        :model="originQuery"
      >
        <el-form-item label="经销商名称">
          <el-input v-model="originQuery.dealerName" />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleQuery"
          >
            查询
          </el-button>
          <el-button @click="handleReset">
            重置
          </el-button>
          <el-button
            type="primary"
            :disabled="loading"
            @click="handleExport"
          >
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </section>
    <!-- table list -->
    <section class="w-100vw">
      <el-button
        type="primary"
        @click="handleAddClick"
      >
        新增
      </el-button>

      <el-table
        ref="table"
        :data="tableList"
        border
        width="100%"
      >
        <el-table-column
          label="序号"
          type="index"
          width="50"
        >
          <template #default="scope">
            <span>{{ (query.num - 1) * query.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          width="250"
          label="经销商ID"
          prop="dealerNo"
        />
        <el-table-column
          width="300"
          label="经销商名称"
          prop="dealerName"
        />

        <el-table-column
          width="250"
          label="操作"
        >
          <template #default="scope">
            <button
              class="edit-btn"
              @click="handleEditClick(scope.row)"
            >
              编辑
            </button>
            <button
              class="edit-btn"
              @click="handleDelClick(scope.row)"
            >
              删除
            </button>
          </template>
        </el-table-column>
      </el-table>

      <div class="text-center py-4">
        <el-pagination
          v-model:current-page="query.num"
          background
          :total="total"
          :page-size="query.size"
          @current-change="getList"
        />
      </div>
    </section>
    <!-- 经销商 新增、编辑 弹窗 -->
    <el-dialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      width="440px"
    >
      <p
        v-if="dialogType === 'del'"
        class="pd20"
      >
        删除该经销商，数据报表内相关联的经销商信息都将被删除，请谨慎操作。
      </p>
      <div
        v-else
        class="dis-name"
      >
        <label>经销商名称</label> <el-input v-model="distributionName" />
      </div>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSaveClick"
        >{{ saveOrConfirm }}</el-button>
      </span>
    </el-dialog>
  </Layout>
</template>

<script>
import dayjs from 'dayjs'
import { mapGetters } from 'vuex'
import Layout from '@/layout/index.vue'
import { delDealer, exportDealer, queryDealer, saveDealer} from '@/api/cabin'

export default {
    name: 'Distributor',
    components: {
        Layout
    },
    data() {
        return {
            total: 0,
            loading: false,
            query: {
                num: 1,
                size: 10
            },
            tableList: [],
            originQuery: {
                id: '', // 经销商ID 编辑、删除 使用
                dealerName: '' // 查询 - 经销商名称
            },
            dialogType: 'add', // add: 新增、edit：编辑、del：删除
            dialogVisible: false,
            saveOrConfirm: '确认',
            distributionName: '', // 新增、编辑弹窗字段
            dialogTitle: '新增经销商'
        }
    },
    created() {
        if (this.cabinId) {
            this.query.shippingSpaceId = this.cabinId
            this.$store.dispatch('cabin/setCabinId', null)
        }

        this.handleQuery()
    },
    computed: {
        ...mapGetters({
            cabinId: 'cabin/getCabinId'
        })
    },
    methods: {
        /**
        *@Description 查询.
        *@Return .
       **/
        async handleQuery() {
            this.query = { ...this.query, ...this.originQuery }
            this.query.num = 1
            this.query.size = 10
            this.getList()
        },
        /**
       *@Description 重置.
       *@Return .
       **/
        handleReset() {
            this.originQuery.dealerName = ''
            this.handleQuery()
        },
        /**
        *@Description 获取经销商列表.
        *@Return .
       **/
        async getList() {
            const params = { ...this.query }

            let res = await queryDealer(params)
            this.total = res.data.total
            this.tableList = res.data.records
        },
        /**
        *@Description 保存 事件监听.
        *@Return .
       **/
        handleAddClick() {
            this.dialogType = 'add' // add: 新增、edit：编辑、del：删除
            this.dialogVisible = true
            this.saveOrConfirm = '保存'
            this.dialogTitle = '新增经销商'
            this.distributionName = ''
            this.originQuery.id = ''
        },
        /**
        *@Description 编辑 事件监听.
        *@Return .
       **/
        handleEditClick(item) {
            console.log(item)
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.saveOrConfirm = '保存'
            this.dialogTitle = '编辑经销商'
            this.distributionName = item.dealerName
            this.originQuery.id = item.id
        },
        /**
        *@Description 删除 事件监听.
        *@Return .
       **/
        handleDelClick(item) {
            console.log(item)
            this.dialogType = 'del'
            this.dialogVisible = true
            this.saveOrConfirm = '确认'
            this.dialogTitle = '删除经销商'
            this.originQuery.id = item.id
        },
        /**
        *@Description 弹窗 保存 、 确认 事件监听.
        *@Return .
       **/
        async handleSaveClick() {
            if (this.dialogType === 'del') {
                await delDealer(this.originQuery.id)
                this.$message.success('删除成功！')
            } else {
                if (this.distributionName.trim() === '') {
                    return this.$message.warning('请输入经销商名称！')
                }
                const params = {
                    id: this.originQuery.id,
                    dealerName: this.distributionName
                }
                await saveDealer(params)
                this.$message.success('保存成功！')
            }
            await this.getList()
            this.dialogVisible = false
        },

        /**
        *@Description 导出.
        *@Return .
       **/
        async handleExport() {

            const params = { ...this.query, ...this.originQuery }

            try {
                this.loading = true
                let res = await exportDealer(params)

                const url = window.URL.createObjectURL(
                    new Blob([res], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    })
                )
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', `经销商_${dayjs().format('YYYY-MM-DD_HH_mm_ss')}.xlsx`)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            } catch (e) {
                console.log('导出异常：', e)
            } finally {
                this.loading = false
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.pd20 {
  padding: 20px 40px;
}
.w-100vw {
  width: calc(100vw - 185px);
}
.dis-name {
  display: flex;
  align-items: center;
  label {
    width: 110px;
  }
}
.edit-btn {
  margin: 0 5px;
  color: #5572fd;
  cursor: pointer;
}
</style>
